<template>
  <div style="margin-top: 65px">
    <sunDrawerBack show="show_permissions" :parent="this.$parent.$parent" />
    <el-page-header class="sun-el-page-header" :content="`管理员【${currentItem.name}】`" @back="goBack" />
    <el-card class="sun-el-card" style="margin-bottom: 94px !important;">
      <el-tree
        ref="my-tree"
        :data="list"
        :default-checked-keys="defaultCheckedKeys"
        node-key="id"
        show-checkbox
        accordion
        check-on-click-node
        :default-expand-all="false"
        :expand-on-click-node="false"
        :render-content="renderContent"
        @check="handleCheckChange"
      />
    </el-card>
    <div class="sun-drawer-base-btn">
      <el-button size="mini" :disabled="is_submit" @click="goBack">取 消</el-button>
      <el-button type="primary" :loading="is_submit" :disabled="!is_redact" size="mini" @click="submit">提 交</el-button>
    </div>
  </div>
</template>

<script>
import { put } from '@/api/request'
import { $tooltips } from '@/sun-components/SunMsg.js'
import SunDrawerBack from '@/sun-components/SunDrawerBack'
export default {
  name: 'AdminRoles',
  components: { SunDrawerBack },
  data() {
    return {
      searchList: [],
      tabList: [],
      defaultCheckedKeys: [],
      permissions_id: [],
      is_submit: false,
      is_redact: false
    }
  },
  computed: {
    list() {
      return this.$parent.$parent.permissionsList
    },
    currentItem() {
      return this.$parent.$parent.currentItem
    },
    show_permissions() {
      return this.$parent.$parent.show_permissions
    }
  },
  watch: {
    show_permissions: {
      handler: function(show) {
        if (show) {
          console.log('打开了', this.$parent.$parent.currentItem.permissions)
          this.$parent.$parent.currentItem.permissions?.forEach(item => {
            this.defaultCheckedKeys.push(item.id)
          })
        }
      }
    }
  },
  created() {
    const _that = this
    if (_that.show_permissions) {
      console.log('打开了', this.$parent.$parent.currentItem.permissions)
      this.$parent.$parent.currentItem.permissions?.forEach(item => {
        this.defaultCheckedKeys.push(item.id)
      })
    }
  },
  methods: {
    renderContent(h, { node, data, store }) {
      node.parent.data.children?.forEach(item => {
        if (item.index) {
          data['requiredIndexId'] = item.id
        }
      })
      return (
        <div>{data.title}</div>
      )
    },
    handleCheckChange(currentData, checkedData) {
      const _that = this
      _that.is_redact = true
      let is_setParent = false
      // 选择非index项
      if (
        // currentData.requiredIndexId &&
        currentData.id !== currentData.requiredIndexId &&
        // !_that.permissions_id.includes(currentData.requiredIndexId) &&
        // checkedData.halfCheckedKeys.length
        _that.$refs['my-tree'].getNode(currentData.id).checked
      ) {
        if (currentData.requiredIndexId) {
          _that.$refs['my-tree'].setChecked(currentData.requiredIndexId, true, false) // 设置index选中
          checkedData.checkedKeys.push(currentData.requiredIndexId) // 需要把setChecked放在提交列表中
        }
        if (!_that.$refs['my-tree'].getNode(currentData.id).parent.parent) {
          _that.$set(_that, 'permissions_id', checkedData.checkedKeys.concat(checkedData.halfCheckedKeys))
          return
        }
        if (!is_setParent) {
          const dataChildren3 = _that.$refs['my-tree'].getNode(currentData.id).parent.parent.parent?.data.children
          dataChildren3?.forEach(el => {
            if (el.index) {
              console.log('处理了3')
              is_setParent = true
              _that.$refs['my-tree'].setChecked(el.id, true, false)
              checkedData.checkedKeys.push(el.id)
            }
          })
        }
        if (!is_setParent) {
          const dataChildren2 = _that.$refs['my-tree'].getNode(currentData.id).parent.parent?.data.children
          dataChildren2?.forEach(el => {
            if (el.index) {
              is_setParent = true
              console.log('处理了2')
              _that.$refs['my-tree'].setChecked(el.id, true, false)
              checkedData.checkedKeys.push(el.id)
            }
          })
        }
        if (!is_setParent) {
          const dataChildren1 = _that.$refs['my-tree'].getNode(currentData.id).parent?.data.children
          dataChildren1?.forEach(el => {
            if (el.index) {
              is_setParent = true
              console.log('处理了1')
              _that.$refs['my-tree'].setChecked(el.id, true, false)
              checkedData.checkedKeys.push(el.id)
            }
          })
        }
        console.log('is_setParent', is_setParent)
        console.log('选择非index项-----当前选项', currentData)
      }
      _that.$set(_that, 'permissions_id', checkedData.checkedKeys.concat(checkedData.halfCheckedKeys))
      // 取消index项
      if (
        // currentData.requiredIndexId &&
        currentData.id === currentData.requiredIndexId &&
        !_that.$refs['my-tree'].getNode(currentData.id).checked
      ) {
        const cancelList = _that.$refs['my-tree'].getNode(currentData.id).parent.childNodes // 根据当前点击的id 获取父级下的所有子项
        _that.setChildNodesChecked(cancelList) // 递归取消数据
        console.log('取消index项-----当前选项', currentData)
      }
    },
    setChildNodesChecked(data) {
      const _that = this
      data?.forEach((cancel, cancel_index) => {
        if (cancel.checked) {
          _that.$refs['my-tree'].setChecked(cancel.data.id, false, false) // 取消选中
          _that.permissions_id.splice(_that.permissions_id.findIndex(arrId => arrId === cancel.data.id), 1) // 移除提交中的id
        }
        if (cancel_index === data.length - 1) { // 移除父级id
          _that.permissions_id.splice(_that.permissions_id.findIndex(arrId => arrId === cancel.data.parent_id), 1)
        }
        if (cancel.parent.level === 2) {
          const parentItem = _that.$refs['my-tree'].getNode(cancel.parent.data.parent_id)
          if (!parentItem.checked && !parentItem.indeterminate) _that.permissions_id.splice(_that.permissions_id.findIndex(arrId => arrId === cancel.parent.data.parent_id), 1)
        }
        cancel.childNodes && cancel.childNodes.length > 0 ? this.setChildNodesChecked(cancel.childNodes) : []
      })
    },
    async submit() {
      if (!this.permissions_id.length) {
        $tooltips('请选择权限!', 'error')
        return
      }
      this.is_submit = true
      await put(`admins/assign/permissions/${this.currentItem.id}`, { permissions: this.permissions_id }).then(response => {
        if (response.code === 0) {
          this.goBack()
          this.$parent.$parent.upData()
        }
        this.is_submit = false
      })
    },
    async goBack() {
      this.$parent.$parent.show_permissions = false
    }
  }
}
</script>
<style lang="scss" scoped>
  @import '@/styles/sun-style.scss';
  .sun-el-card  ::v-deep {
    .el-tree-node__content{
      height: auto !important;
      font-size: 14px;
      line-height: 40px;
      color: #606266;
    }
  }
</style>
